import { invoke } from "@tauri-apps/api/core";
import { useNavigate, useLocation } from "react-router-dom";
import { useState, useRef } from "react";
import { UserInterface } from "./UserInterface.tsx";


export function EditorFunctions(){

  const [content, setContent] = useState("");
  const [fileName, setFileName] = useState("");
  const [error, setError] = useState("");
  const [isSaved, setIsSaved] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();
  const {
    routeInfo
  } = UserInterface();
  const routeinforef = useRef(routeInfo);
  // 加载文件内容
  const loadFileContent = async (path: string) => {
      try {
        console.log("filePath is ", path);
        const metadata = await invoke<{ is_dir: boolean }>("get_path_metadata", { path });
        if(!metadata.is_dir){
          const content = await invoke<string>("read_file_content", { path });
          setContent(content);
          setFileName(location.state.name);
          console.log("open file:", location.state.name);
          setIsSaved(true);
        }else{
          console.log("This is a directory.");
        }
      } catch (error) {
        console.error(error);
        setError(`Failed to read file: ${error}`);
      }
  };

    // 保存文件内容
  const saveFile = async () => {
    try {
        const filePath = location.state.path;
        const encoder = new TextEncoder();
        const bytes = encoder.encode(content);
        const savefilepath = filePath + '\\' + fileName;
        await invoke("write_file_bytes", 
          { path : savefilepath, contents : bytes });
        setIsSaved(true);
        setError("");
    } catch (error) {
      console.error("Failed to save file:", error);
      setError(`Failed to save file: ${error}`);
    }
  };

    // 处理内容变化
  const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
      setContent(e.target.value);
      setIsSaved(false);
  };

    // 处理文件名变化
  const handleFileNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      setFileName(e.target.value);
      setIsSaved(false);
  };

    // 返回文件浏览器
  const handleBack = async () => {
      // 如果有未保存的更改，提示用户
      if (!isSaved) {
        const confirmed = await confirm("You have unsaved changes. Save before leaving?");
        if (confirmed) {
          await saveFile();
        }
      }
      // console.log("oss from text editor", location.state.oss);
      navigate("/files", { state: 
        { 
          path: location.state.path,
          routeInfo: routeinforef.current,
          oss: location.state.oss
        } 
      });
  };

  return{
    routeinforef,
    isSaved,
    error,
    location,
    content,
    fileName, setFileName,
    loadFileContent,
    saveFile,
    handleContentChange,
    handleFileNameChange,
    handleBack
  }
} 